<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\Auth;
use app\admin\validate\DoLogin;
use thans\jwt\facade\JWTAuth;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Session;
use think\facade\View;

class Login
{
    /**
     * 登录页面展示
     * @return string
     *
     */
    public function index()
    {
        View::config(['layout_on'=>false]);
//        $cache = Cache::get('userLogin');
//        if ($cache){
//            return redirect('/admin/index');
//        }
        return View::fetch('login/login');
    }

    /**
     * 用户登录
     * 验证信息
     * @param Admin $admin
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function dologin(Admin $admin,Auth $auth)
    {
        try {
            $data = request()->all();
            validate(DoLogin::class)->check($data);
            $arr = $admin->where('username',$data['username'])->find();
            if ($arr){
                if ($arr['password'] == encrypt_password($data['password'])){
                    session('name',$arr['username']);
                    if (!empty($data['online'])){
                        cache('userLogin',$arr['username'].'已登录',86400);
                    }
                    if ($arr['role_id'] != 1){
                        $result = $admin->with('role')->find($arr['id'])->toArray();
                        $auths = $auth->field('id,auth_name,pid,auth_c,auth_a')->whereIn('id',$result['role_auth_ids'])->select()->toArray();
                        $res = [];
                        foreach ($auths as $value){
                            $res[] = $value['auth_c'].'/'.$value['auth_a'];
                        }
                        cache($arr['username'],$res);
                    }
                    $admin->where('id',$arr['id'])->update([
                        'last_login_time' => time(),
                    ]);
                    abort(200,'登录成功');
                }
                abort(2003,'密码错误');
            }
            abort(2002,'用户不存在');
        } catch (ValidateException $exception){
            return success(2001,$exception->getError());
        } catch (HttpException $exception){
            return success($exception->getStatusCode(),$exception->getMessage(),$exception->getHeaders());
        }
    }
}
